<?php

error_reporting(E_ALL ^ E_NOTICE);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\cache\brand\BrandWikiBuyAndFavCache;
use Biz\model\wiki\Wiki as mWiki;
use Doraemon\pockets\config\IniConfig;
use Doraemon\tools\Log;
use Doraemon\tools\Presto\PrestoClientV2;

$wikiMaxId = mWiki::get('id', ['LIMIT' => 1, 'ORDER' => ['id' => 'DESC']]);
$pageSize = 5000;

$page = ceil($wikiMaxId / $pageSize);
$config = IniConfig::getConfigSelect('presto', 'brand');
$presto = new PrestoClientV2("{$config['host']}:{$config['port']}/{$config['path']}", "hive", $config["username"],
    $config["password"]);
$i = 0;
try {
    while ($i < $page) {
        try {
            $start = $i * $pageSize;
            $end = ($i + 1) * $pageSize;
            $presto->Query("select wiki_id,type,uid from oss.hhz.app_wiki_card_optimize_project where day=#{date-1,yyyyMMdd} and wiki_id >$start and  wiki_id<=  $end");
            $presto->WaitQueryExec();
        } catch (\Doraemon\tools\Presto\PrestoException $e) {
            Log::error('从metabase获取wiki被用户点击购买以及收藏的行为数据'.$e);
        }
        $uidArr = $presto->GetData();
        echo '这是第'.($i + 1).'批数据处理开始,共：'.(count($uidArr)).'条数据'.PHP_EOL;
        Log::info('这是第'.($i + 1).'批数据处理开始,共：'.(count($uidArr)).'条数据');
        if ($uidArr) {
            $buyWikiUidArr = [];
            $favWikiUidArr = [];
            foreach ($uidArr as $v) {
                if ($v[1] == 'buy') {
                    $buyWikiUidArr[$v[0]][] = $v[2];
                } else {
                    $favWikiUidArr[$v[0]][] = $v[2];
                }
            }
            if ($buyWikiUidArr) {
                foreach ($buyWikiUidArr as $wikiId => $v) {
                    BrandWikiBuyAndFavCache::addData($wikiId, 'buy', $v);//数据落地
                }
            }
            if ($favWikiUidArr) {
                foreach ($favWikiUidArr as $wikiId => $value) {
                    BrandWikiBuyAndFavCache::addData($wikiId, 'fav', $value);//数据落地
                }
            }
        }
        echo '这是第'.($i + 1).'批数据处理结束,共：'.(count($uidArr)).'条数据被处理'.PHP_EOL;
        Log::info('这是第'.($i + 1).'批数据处理结束,共：'.(count($uidArr)).'条数据被处理');
        $i++;
    }
} catch (Exception $exception) {
    Log::info('同步wiki被用户点击购买以及收藏的行为数据异常',['exception'=>$exception]);
}
